import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { gpsService } from '../../../../service/gps/gps.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import {insService} from "../../../../service/ins/ins.service";
import {ProductService} from "../../../../service/prod/product.service";

@Component({
  selector: 'gps-add',
  templateUrl: './gps-add.component.html',
  styleUrls: ['./gps-add.component.less']
})
export class gpsAddComponent implements OnInit, OnDestroy {
  product:  any = {
    id:null,
    orderNo: null,
    bpmStatus:null,
    cusName:null,
    orderAmount:null,
    orderType:null,
    carNo:null,
    carType:null,
    carVin:null,
    gpsBrand:null,
    gpsType:null,
    gpsDate:null,
    gpsTime:null, /* no show */
    gpsUser:null,
    gpsMobile:null,
    gpsAddr:null,
    gpsStatus:null,
    gpsRemark:null,
    installAttaNo:null,
    installUser:null,
    installDate:null,
    installId1:null,
    installId2:null,
    installId3:null,
    installId4:null,
    installId5:null,
    gpsBy1:null,
    gpsBy2:null,
    gpsBy3:null,
    gpsBy4:null,
    gpsBy5:null,
    gpsBy6:null,
    gpsBy7:null,
    gpsBy8:null
  };
  bpmStatus =  [{text: '未抵押', value: '1'}, {text: '已抵押', value: '10'}];

  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;
  private sub: any;

  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;

  uploadUrl = '';
  avatarParam = { sbtype: 'No',  filetype:'ma',orderNo: 'no'};
  fileList = [ ];
  avatarUrl:string;
  loading = false;


  constructor(
    private productService: ProductService,

    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private gpsService: gpsService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

  ngOnInit(): void {

    // this.loadbpmStatus();

    this.uploadUrl = this.productService.uploadUrl();

    // 获取参数
    // this.sub = this.route.params.subscribe(params => {
    //   this.product.id = params["id"]
    //   console.log("this.product.id****************"+this.product.id);
    //   // 获取商品详情
    //   this.getProductInfo();
    //   // this.getfileList(this.product.id);

    // });
    // 隐藏reusetab
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 1000);
  }
  loadbpmStatus() {
    this.bpmStatus = [];
    this.comm.getType("bpm_status").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.bpmStatus.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  // 显示reusetab
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误
    Promise.resolve(null).then(() => this.tabIndex = index);
  }



  getProductInfo() {
    this.gpsService.getProduct(this.product.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.product = data.data;
      this.avatarParam = { sbtype: 'No',  filetype:'ma',orderNo: this.product.orderNo};
      this.titleService.setTitle("编辑产品");
      this.getfileList(this.product.orderNo);
    })
  }
  getfileList(id) {
    this.productService.getfileList(id,"ma").pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {

    console.log("gps*****************"+JSON.stringify(data));

      if (data.data.length > 0) {
        let flag = 0;
        for (const detail of data.data) {
          this.fileList.push( {
            uid: flag,
            name: detail.attaName,
            status: 'done',
            url: detail.attaUrl,
            id: detail.id
          } )
          flag++;
        }
      };
    })
  }




  back() {
    this.router.navigate(['/gps/gps']);
  }


  save() {


    let fxjgpss = {
      updateBy:this.setting.user.username,
      id:this.product.id,
      orderNo: this.product.orderNo,
      bpmStatus:this.product.bpmStatus,
      cusName:this.product.cusName,
      orderAmount:this.product.orderAmount,
      orderType:this.product.orderType,
      carNo:this.product.carNo,
      carType:this.product.carType,
      carVin:this.product.carVin,
      gpsBrand:this.product.gpsBrand,
      gpsType:this.product.gpsType,
      gpsDate:this.product.gpsDate,
      gpsTime:this.product.gpsTime,
      gpsUser:this.product.gpsUser,
      gpsMobile:this.product.gpsMobile,
      gpsAddr:this.product.gpsAddr,
      gpsStatus:this.product.gpsStatus,
      gpsRemark:this.product.gpsRemark,
      installAttaNo:this.product.installAttaNo,
      installUser:this.product.installUser,
      installDate:this.product.installDate,
      installId1:this.product.installId1,
      installId2:this.product.installId2,
      installId3:this.product.installId3,
      installId4:this.product.installId4,
      installId5:this.product.installId5,
      gpsBy1:this.product.gpsBy1,
      gpsBy2:this.product.gpsBy2,
      gpsBy3:this.product.gpsBy3,
      gpsBy4:this.product.gpsBy4,
      gpsBy5:this.product.gpsBy5,
      gpsBy6:this.product.gpsBy6,
      gpsBy7:this.product.gpsBy7,
      gpsBy8:this.product.gpsBy8
    };

    // 调用接口
    this.gpsService.addGps(fxjgpss).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if (data.ok === true) {
        this.msg.success('创建成功');
        this.emit.sendMessage("RELOAD_GOODS_LIST");
        setTimeout(() => {
          this.router.navigate(['gps/gps']);
        }, 500);
      } else {
        this.msg.error(data['message']);
      }
    })
  }

  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      this.msg.warning('图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl = img;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }


   // 图片 wuwq
   upLoadChange(event) {
    console.log(event);
    let file = event ? event.file : null;
    console.log(file);
    let datas = file && file.id ? file : file.response;
    console.log(datas);
    if (datas) {
        if (event.type == 'success') {
            console.log('ss');
        } else if (event.type == 'removed') {
          console.log('aa');
          let picId = file.id ? file.id : file.response[0].fileId
          this.delPic(picId);
        }
    }
  }


  // 删除图片 wuwq
  delPic(id) {
    this.gpsService.delfile(id).pipe(
        catchError(err => {
          return of(err);
        })
      ).subscribe(data => {
        if(data.ok){
          // this.productorder = data.data;
          // console.log(this.productorder);
          // this.reload();
        }else{
          console.log("22")
        }
      })
  }



}
